package com.crazy.web.interceptor;

import com.crazy.enums.Constants;
import com.crazy.exception.CommonException;
import com.crazy.rest.RestResult;
import lombok.extern.log4j.Log4j2;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.ValidationException;

/**
 * Controller 增强器
 */
@Log4j2
@ControllerAdvice
public class MyControllerAdvice {

    /**
     * 自定义错误
     * @param ex
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = CommonException.class)
    public RestResult errorHandler(CommonException ex) {
        log.error(Constants.ERROR, ex);
        return RestResult.createFailedResult("系统出错，请联系管理员");
    }

    /**
     * 系统错误异常
     * @param ex
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public RestResult errorHandler(Exception ex) {
        log.error(Constants.ERROR, ex);
        return RestResult.createFailedResult(ex.getMessage());
    }

    /**
     * 权限不足异常
     * @param ex
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = UnauthorizedException.class)
    public RestResult errorHandler(UnauthorizedException ex) {
        log.error(Constants.ERROR, ex);
        return RestResult.createFailedResult("权限不足，请联系管理员");
    }

    /**
     * 用户名密码错误
     * @param ex
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = AuthenticationException.class)
    public RestResult errorHandler(AuthenticationException ex) {
        log.error(Constants.ERROR, ex);
        return RestResult.createFailedResult("用户名密码错误");
    }

    /**
     * 验证不通过
     * @param ex
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = ValidationException.class)
    public RestResult errorHandler(ValidationException ex) {
        log.error(Constants.ERROR, ex);
        return RestResult.createFailedResult(ex.getMessage());
    }

}
